//
//  RewardViewController.m
//  DaJiang
//
//  Created by sally on 16/9/29.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CellManager.h"
#import "FeedbackView.h"
#import "MainModel.h"
#import "OtherModel.h"
#import "RewardViewController.h"
#import "PickerView.h"

@interface RewardViewController () <UITextViewDelegate,UIPickerViewDelegate, UIPickerViewDataSource,PickerViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) NSString *price;
@property (strong, nonatomic) NSString *time;
@property (strong, nonatomic) NSString *loc;
@property (strong, nonatomic) NSString *locDesc;
@property (strong, nonatomic) NSString *companyName;
@property (strong, nonatomic) NSString *userName;
@property (strong, nonatomic) NSString *phone;
@property (strong, nonatomic) NSString *problem;
@property (strong, nonatomic) PickerView *timePicker; //时间选择器
@property (strong, nonatomic) PickerView *locPicker;  //区域选择器
@property (strong, nonatomic) NSMutableArray *timeArr;
@property (strong, nonatomic) NSMutableArray *locArr;
@property (strong, nonatomic) NSMutableArray *loc2Arr;


@end

@implementation RewardViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 设置通知
- (void)setNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark 初始化控件
- (void)initControl {
  self.title = @"悬赏请专家";
  self.headerView.height = GHeadViewHeight;
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.timeArr = [[NSMutableArray alloc] init];
  self.locArr = [[NSMutableArray alloc] init];
  self.loc2Arr = [[NSMutableArray alloc] init];
  [self.tableData addObject:@[ @"悬赏金额" ]];
  [self.tableData addObject:@[ @"时间", @"区域", @"地点" ]];
  [self.tableData addObject:@[ @"企业名称", @"联系人", @"联系方式" ]];
  [self.tableData addObject:@[ @"提问问题", @"" ]];
  [self initControlText];

  [TimeModel queryTimeWithCompletion:^(NSMutableArray *timeList) {
    if (timeList) {
      [self.timeArr removeAllObjects];
      self.timeArr = timeList;
    } else {
      NSError *error = [TimeModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];

  [LocModel queryLocWithCompletion:^(NSMutableArray *locList) {
    if (locList) {
      [self.locArr removeAllObjects];
      self.locArr = locList;
      
      //加载分类2列表数据
      [self loadLoc2Data:self.locArr[0] fromPicker:NO];
    } else {
      NSError *error = [LocModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];

}

#pragma mark 初始化控件数据
- (void)initControlText {
  self.companyName = @"";
  self.userName = @"";
  self.phone = @"";
  self.problem = @"";
  self.price = @"";
  self.time = @"";
  self.loc = @"";
  self.locDesc = @"";
}

#pragma mark - action
#pragma mark 点击提交
- (IBAction)actionOnSend:(id)sender {
  if (self.price.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入悬赏金额"];
    return;
  }
  if (![OperationManager validateMoney:self.price]) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入正常格式的悬赏金额"];
    return;
  }
  if ([self.price floatValue] <= 0) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入大于0的悬赏金额"];
    return;
  }
  if (self.time.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入时间"];
    return;
  }
  if (self.loc.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入区域"];
    return;
  }
  if (self.locDesc.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入地点"];
    return;
  }
  if (self.companyName.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入企业名称"];
    return;
  }
  if (self.userName.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入联系人"];
    return;
  }
  if (self.phone.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入联系方式"];
    return;
  }
  if (![OperationManager isMobileNumber:self.phone]) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入正常格式的联系方式"];
    return;
  }
  if (self.problem.length < 1) {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请填入提问问题"];
    return;
  }

  MBProgressHUD *hud = [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
  [MainModel privateRequestWithCompanyName:self.companyName userName:self.userName phone:self.phone problem:self.problem rewardValue:self.price time:self.time location:self.loc locationDesc:self.locDesc completion:^(BOOL isSucceed) {
    if (isSucceed) {
      FeedbackView *feedbackView = [[FeedbackView alloc] initWithFeedbackType:FeedbackType_Reward];
      [feedbackView show];
      //清理编辑框里面数据
      [self initControlText];
      [self.tableView reloadData];
    } else {
      NSError *error = [MainModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    hud.hidden = YES;
  }];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return self.tableData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [[self.tableData objectAtIndex:section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return 0.1; //section头部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  return GNormalMargin; //section底部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 3 && indexPath.row == 1) { //最后一项
    return GTextViewHeight - NavHeight;
  }
  return NavHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  UITableViewCell *cell;
  if (indexPath.section == 1 && (indexPath.row == 0 || indexPath.row == 1)) {
    //主副标题形式
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;

    //副标题
    [CellManager configCellDetailText:cell];
    if (indexPath.row == 0) { //时间
      cell.detailTextLabel.text = self.time;
    } else { //区域
      cell.detailTextLabel.text = self.loc;
    }
  } else {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    //编辑行
    if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2) {
      UITextField *textField = [CellManager configCellNormalTextField:cell];
      //tag数值
      NSInteger tag = indexPath.section * 3 + indexPath.row;
      textField.tag = tag;
      switch (tag) {
        case 0:
          textField.text = self.price;
          break;
        case 5:
          textField.text = self.locDesc;
          break;
        case 6:
          textField.text = self.companyName;
          break;
        case 7:
          textField.text = self.userName;
          break;
        case 8:
          textField.text = self.phone;
          break;
        default:
          break;
      }

      [cell.contentView addSubview:textField];
    }

    //编辑框
    if (indexPath.section == 3 && indexPath.row == 1) { //最后一项
      UITextView *textView = [CellManager configCellTextView:cell];
      textView.text = self.problem;
      textView.delegate = self;
      [cell.contentView addSubview:textView];
    }
  }
  //主标题
  [CellManager configCellNormalText:cell];
  cell.textLabel.text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

  return cell;
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失
  
  if (indexPath.section == 1 && indexPath.row == 0) {//时间
    self.timePicker = [[PickerView alloc] initWithPickerType:PickerType_Loc];
    self.timePicker.delegate = self;
    [self.timePicker show];
    
    //重载cell
    TimeModel *timeModel = self.timeArr[0];
    self.time = [NSString stringWithFormat:@"%@小时", timeModel.data.choose_time];
    [self reloadTimeCell];
  } else if (indexPath.section == 1 && indexPath.row == 1) {//区域
    self.locPicker = [[PickerView alloc] initWithPickerType:PickerType_ExpertSort];
    self.locPicker.delegate = self;
    [self.locPicker show];
    
    //重载cell
    LocModel *locModel = self.locArr[0];
    LocModel *locModel2 = self.loc2Arr[0];
    self.loc = [NSString stringWithFormat:@"%@，%@", locModel.name,locModel2.name];
    [self reloadLocCell];
  }
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
  self.problem = textView.text;
}

#pragma mark Picker Data Source Method
// 返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
  if ([pickerView isEqual:self.locPicker.pickerView]) { //区域
    return 2;
  } else { //时间
    return 1;
  }
}

// 返回该列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  if ([pickerView isEqual:self.locPicker.pickerView]) { //区域
    if (component == 0) {
      return self.locArr.count;
    } else {
      return self.loc2Arr.count;
    }
  } else { //时间
    return self.timeArr.count;
  }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
  if ([pickerView isEqual:self.locPicker.pickerView]) { //区域
    
    if (component == 0) {
      LocModel *locModel = [self.locArr objectAtIndex:row];

      //加载地区2的数据
      UIWindow *window = [UIApplication sharedApplication].keyWindow;
      [[CommonMethod sharedCommonMethod] createProgressHUDInView:window withMessage:@""];
      [self loadLoc2Data:locModel fromPicker:YES];
    } else {
      LocModel *locModel2 = [self.loc2Arr objectAtIndex:row];
      NSRange range = [self.loc rangeOfString:@"，"];
      self.loc = [NSString stringWithFormat:@"%@，%@",[self.loc substringToIndex:range.location],locModel2.name];
      //重载cell
      [self reloadLocCell];
    }

  } else { //时间
    TimeModel *time = [self.timeArr objectAtIndex:row];
    self.time = [NSString stringWithFormat:@"%@小时", time.data.choose_time];
    
    //重载cell
    [self reloadTimeCell];
  }
}

#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  if ([pickerView isEqual:self.locPicker.pickerView]) { //区域
    if (component == 0) {
      LocModel *locModel = [self.locArr objectAtIndex:row];
      return locModel.name;
    } else {
      LocModel *locModel2 = [self.loc2Arr objectAtIndex:row];
      return locModel2.name;
    }
  } else { //时间
    TimeModel *time = [self.timeArr objectAtIndex:row];
    return [NSString stringWithFormat:@"%@小时", time.data.choose_time];
  }
}

#pragma mark PickerViewDelegate
- (void)cancelSelect:(UIView *)picker{
  if (picker == self.timePicker) {
    self.time = @"";
    [self reloadTimeCell];
  }else if (picker == self.locPicker){
    self.loc = @"";
    [self reloadLocCell];
  }
}

#pragma mark - 私有方法
#pragma mark textfield中的文本发生改变时
- (void)textFieldChanged:(NSNotification *)notification {
  UITextField *textField = (UITextField *) notification.object;
  switch (textField.tag) {
    case 0:
      self.price = textField.text;
      break;
    case 5:
      self.locDesc = textField.text;
      break;
    case 6:
      self.companyName = textField.text;
      break;
    case 7:
      self.userName = textField.text;
      break;
    case 8:
      self.phone = textField.text;
      break;
    default:
      break;
  }
}

#pragma mark 加载地区2列表数据
- (void)loadLoc2Data:(LocModel *)loc fromPicker:(BOOL)fromPicker {
  [LocModel queryCityWithLoc:loc.code completion:^(NSMutableArray *locList) {
    if (locList) {
      [self.loc2Arr removeAllObjects];
      
      if (locList.count == 2) {//直辖市，需要访问三级接口
        
        for (LocModel *item in locList) {
          [LocModel queryCity2WithLoc:item.code completion:^(NSMutableArray *cityList) {
            if (cityList) {
              [self.loc2Arr addObjectsFromArray:cityList];
              
              if (fromPicker) {
                LocModel *locModel2 = [self.loc2Arr objectAtIndex:0];
                self.loc = [NSString stringWithFormat:@"%@，%@", loc.name,locModel2.name];
                [self.locPicker.pickerView reloadAllComponents];
                //重载cell
                [self reloadLocCell];
              }

            } else {
              NSError *error = [LocModel getLastError];
              [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
            }
          }];
        }
        
      }else{//省
        
        [self.loc2Arr addObjectsFromArray:locList];
        
        if (fromPicker) {
          if (self.loc2Arr.count > 0) {
            LocModel *locModel2 = [self.loc2Arr objectAtIndex:0];
            self.loc = [NSString stringWithFormat:@"%@，%@", loc.name,locModel2.name];
          }else{
            self.loc = loc.name;
          }
          [self.locPicker.pickerView reloadAllComponents];
          //重载cell
          [self reloadLocCell];
        }

      }

    } else {
      NSError *error = [LocModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [MBProgressHUD hideAllHUDsForView:window animated:YES];
  }];
}

#pragma mark 重载时间cell
- (void)reloadTimeCell {
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
  [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark 重载区域cell
- (void)reloadLocCell {
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
  [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}


@end
